package com.alibaba.sdk.config.shiro;

import com.alibaba.sdk.constant.ApplicationErrorConstant;
import com.alibaba.sdk.model.OperationResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 异常信息处理
 *
 * @ writer Shawn(Shawn_0217@163.com)
 * @ date & time 2021/4/27 0:49
 * @ company alibaba
 */
@Slf4j
@Order(-3)
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class ShiroExceptionHandler {

    /**
     * 处理登录异常
     *
     * @return
     */
    @ExceptionHandler({UnauthenticatedException.class, AuthenticationException.class})
    @ResponseBody
    public OperationResult authorizedException(Exception e) {
        log.warn("用户未登录", e);
        return OperationResult.failWithCode(ApplicationErrorConstant.USER_NO_LOGIN);
    }

    /**
     * 处理无权限异常
     *
     * @return
     */
    @ExceptionHandler({AuthorizationException.class, UnauthorizedException.class})
    @ResponseBody
    public OperationResult authorizationException(Exception e) {
        log.warn("用户无权限", e);
        return OperationResult.failWithCode(ApplicationErrorConstant.HAS_NO_AUTHORIZATION);
    }
}